import os
import sys

def count_likes(file_path):
    """统计每种兴趣的报名人数"""
    like_count = {}
    
    try:
        with open(file_path, 'r', encoding='utf-8') as fin:
            for line_num, line in enumerate(fin, 1):
                try:
                    # 安全处理换行符和空白
                    line = line.strip()
                    
                    # 跳过空行
                    if not line:
                        continue
                        
                    # 分割姓名和兴趣列表
                    parts = line.split(" ")
                    if len(parts) < 2:
                        print(f"警告: 第 {line_num} 行格式错误 - '{line}'")
                        continue
                        
                    sname, likes = parts[0], parts[1]
                    
                    # 分割兴趣列表
                    like_list = likes.split(",")
                    
                    # 统计每种兴趣
                    for like in like_list:
                        like_count[like] = like_count.get(like, 0) + 1
                        
                except Exception as e:
                    print(f"处理第 {line_num} 行时出错: {str(e)} - '{line}'")
                    continue
                    
    except FileNotFoundError:
        print(f"错误: 文件不存在 - {file_path}")
        return None
    except PermissionError:
        print(f"错误: 无权限读取文件 - {file_path}")
        return None
    except UnicodeDecodeError:
        print(f"错误: 文件编码问题 - 请确保文件是 UTF-8 格式")
        return None
    except Exception as e:
        print(f"读取文件时出错: {str(e)}")
        return None
        
    return like_count

def main():
    # 构建文件路径
    file_path = os.path.join(os.getcwd(), "01-exercise", "21-40", "data", "student_like.txt")
    
    # 统计兴趣
    result = count_likes(file_path)
    
    # 检查结果并输出
    if result is None:
        print("统计失败，请检查错误信息")
        sys.exit(1)
        
    if not result:
        print("未找到有效数据")
        return
        
    print("兴趣报名人数统计:")
    print("=" * 30)
    for interest, count in result.items():
        print(f"{interest}: {count}")
    print("=" * 30)

if __name__ == "__main__":
    main()